import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 页面组件导入
import LoginPage from '@/pages/LoginPage.vue'
import DashboardPage from '@/pages/DashboardPage.vue'
import VehicleManagementPage from '@/pages/VehicleManagementPage.vue'
import ApplicationManagementPage from '@/pages/ApplicationManagementPage.vue'
import DriverManagementPage from '@/pages/DriverManagementPage.vue'
import ExpenseManagementPage from '@/pages/ExpenseManagementPage.vue'
import SystemSettingsPage from '@/pages/SystemSettingsPage.vue'
import MainLayout from '@/components/MainLayout.vue'

// 定义路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: LoginPage,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: '/dashboard',
        name: 'dashboard',
        component: DashboardPage
      },
      {
        path: '/vehicles',
        name: 'vehicles',
        component: VehicleManagementPage
      },
      {
        path: '/applications',
        name: 'applications',
        component: ApplicationManagementPage
      },
      {
        path: '/drivers',
        name: 'drivers',
        component: DriverManagementPage
      },
      {
        path: '/expenses',
        name: 'expenses',
        component: ExpenseManagementPage
      },
      {
        path: '/settings',
        name: 'settings',
        component: SystemSettingsPage
      }
    ]
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化用户状态
  if (!userStore.isLoggedIn) {
    userStore.initUser()
  }
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
